package engine.newUi
{
	import engine.control.MiniLoadingBar;
	import engine.control.loading.MultLoader;
	import engine.data.BindManage;
	import engine.data.ModelLocator;
	import engine.logic.login.PlayCDTimerLogic;
	import engine.logic.tips.TipsManage;
	import engine.net.event.CustomMsgEvent;
	import engine.net.messages.CustomToClientFlag;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.SystemSender;
	
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.events.TimerEvent;
	import flash.geom.Point;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.utils.Timer;
	import flash.utils.setTimeout;
	
	import newx.StageInfo;
	import newx.com.config.StaticIni;
	import newx.com.control.text.NxLabel;
	import newx.com.control.window.NxWindowEvent;

	/**
	 * 五子棋逻辑 
	 * @author zhouqiang
	 * 
	 */	
	public class GobangLogic
	{
		private static var _self:GobangLogic;
		
		private var _ui:GobangUI;
		
		private var _model:ModelLocator;
		
		private var _bind:BindManage;
		
		private var _bindIndex	:int		=	-1;
		private var _bindScoreIndex:int	=	-1;
		private var _bindGoldIndex	:int	=	-1;
		
		/**棋子数组*/
		private var chessArr:Array;	
		
		/**棋盘*/
		private var chessboard:MovieClip;
		
		/**延时时间*/
	//	private var _timer:Timer;
		
		/**CD计时器*/
		private var _CDtimer:Timer;
		
		/**服务器时间*/
		private var _serverTime:int;
		
		/**结束时间*/
		private var _overTime:int;
		
		/**CD时间*/
		private var _CDTimeCount:int	= 1;
		
		private var _score:int;
		private var _chessInfoArr:Array	=	[];
		
		private var _load:Loader;
		
		public function GobangLogic()
		{
		}
		
		public static function getInstance():GobangLogic
		{
			if(_self == null)
			{
				_self =new GobangLogic();
			}
			return _self;
		}
		
		public function  Init():void
		{
			chessArr	=	[];
			_model		=	ModelLocator.getInstance();
			_bind		=	BindManage.getInstance();
//			loadChess();
			initGroup();
			
		}
		
		public function BeforeShow():void
		{
			isCanSeeChess();
			ui.beginBtn.visible	=	false;
			ui.shortBtn.visible	=	false;
			loadChess();
		}

		private function updataView():void
		{
			_CDtimer	=	new Timer(1000);
			addEvent();
			if(_bindIndex == -1)
			{
				//_bindIndex	= _bind.BindRecord(_model.scene,"ChessboardRec",addChessFun,removeChesskFun)
			}
			if(_bindScoreIndex == -1)
			{
				_bindScoreIndex	=	_bind.BindProp(_model.scene.Role,"ChessGetScore",this,"bindScoreCall");
			}
			if(_bindGoldIndex == -1)
			{
				_bindGoldIndex	=	_bind.BindProp(_model.scene.Role,"ChessGetGoldCoin",this,"bindGoldCall");
			}
			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_CHESSOVER_TIME),isBegin);
			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_SENDSERVERTIME),getServerTime);
			//_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_SHOW_GEN_CHESS_BEFORE_CLEAR),haveRefresh);
			
			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_CUR_CHESS_LAYOUT),getAllChessinfo);
			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_ONE_CLICK_CLEAR_RESULT),getChessInfo);
			//得到排行榜数据
			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_SEND_CHESS_SCORE_TOPLIST),getRankLiat);
			//
			var maxScore:int	=	_model.scene.Role.GetProperties("ChessMaxScore");	
			var money:int		=	_model.scene.roleLevel *800;
			if(chessboard != null)
			{
				(chessboard.getChildByName("txt4") as TextField).text	=		money.toString();
			}
			
			//是否开始下棋了
			if(_model.scene.Role.GetProperties("IsChessStarted") == 0)
			{
				ui.beginBtn.visible	=	true;
				ui.shortBtn.visible	=	true;
			}
			else
			{
				ui.beginBtn.visible	=	false;
				ui.shortBtn.visible	=	false;
			}
			CDtimeHandle();
		}
			
		/**
		 * 得到服务器当前时间 
		 * @param e
		 * 
		 */		
		private function getServerTime(e:CustomMsgEvent):void
		{
			_serverTime			=	e.pList[0];
			_CDTimeCount		=	_overTime-_serverTime;
//			if(_CDTimeCount > 0)
//			{
//				//beginGame(true);
//			}
//			else
//			{
//				//beginGame(false);
//			}
			_CDtimer.stop();
			_CDtimer.start();
		}
		
		/**
		 * 得到整个棋盘信息 
		 * @param e
		 * 
		 */		
		private function getAllChessinfo(e:CustomMsgEvent):void
		{
			var arr:Array	=	e.pList;
			_chessInfoArr	=	[];
			var mc:MovieClip;
			for(var i:int = 0; i < 6;i++)
			{
				var tempArr:Array	=	new Array();			
				for(var j:int	=	0; j < 6;j++)
				{
					tempArr.push(int(arr[j+i*6]));
					(chessArr[i][j] as MovieClip).gotoAndStop(int(arr[j+i*6]));
				}
				_chessInfoArr.push(tempArr);
			}	
			isCanSeeChess(true);
		}
		
		/**
		 * 每次点击棋子后得到变换过的棋子的信息 
		 * @param e
		 * 
		 */		
		private function getChessInfo(e:CustomMsgEvent):void
		{
			
			ui.whiteChess.visible	=	false;
			ui.blackChess.visible	=	false;
			var length:int 		=	e.pList[0];
			if(e.pList.length <= 0)
			{
				beginGame(true);
				//ui.chessGroup.mouseChildren	=	true;
				return
			}
			var _strArr:String  = e.pList[1];
			var arr1:Array		=	e.pList.slice(1);
			var str:String		=	_strArr ; 
			
			var arr:Array		=	setArray(_strArr.split("|"));
			var tempArr:Array	=	new Array();
			for( var i:int = 0; i < arr.length;i++ )
			{
				var pointArr:Array	=	arr[i] 
				if( pointArr.indexOf("") >= 0 )pointArr.splice(pointArr.indexOf(""),1);
//				if( pointArr.indexOf("") >= 0 )pointArr.splice(pointArr.indexOf(""),1);
				tempArr.push(pointArr);
			}
		
			
			changeChess(tempArr,0,length);
		}
		private function setArray(arr:Array):Array
		{
			if(arr.length==0 ||arr==null||arr[0]=="")return null; 
			
			var i:int = 0 ; 
			var arr_2:Array = [] ; 
			for( i ; i<arr.length ; i++)
			{
				var str:String  = "";
				str = String(arr[i]);
				var arr_3:Array = [] ; 
				for(var j:int =0 ; j<str.length ; j++)
				{
					arr_3.push(str.charAt(j)); 
				}
				arr_2.push(arr_3) ; 
			}
			return arr_2
		}
		/**
		 * 得到排行榜数据 
		 * @param e
		 * 
		 */		
		private function getRankLiat(e:CustomMsgEvent):void
		{
			var arr:Array	= e.pList;
			var str:String	=	"";
			var rank:String;//名次
			var NameStr:String;//名字
			var scoreStr:String	=	"";//积分
			var count:int	=	1;
			var txt:TextField	=	chessboard.getChildByName("txt5") as TextField;
			txt.htmlText		=	"";
			txt.text			=	"";
			var scoreTxt:TextField	=	chessboard.getChildByName("txt6") as TextField;
			scoreTxt.htmlText	=	"";
			//前3个是自己是否进榜，还有自己的名次
			for( var i:int= 3;i < arr.length;i+=2 )
			{
				NameStr		=	arr[i];
				rank		=	count.toString();
				str			=	str.concat(rank+"\t"+NameStr);
				scoreStr	=	scoreStr.concat(arr[i+1]);
				if(arr[i] == _model.scene.Role.GetProperties("Name"))
				{
					str			=	"<font color='#f00000'>"+str+"</font>";
					scoreStr	=	"<font color='#f00000'>"+scoreStr+"</font>";
				}
				str			=	str.concat("<br>");
				scoreStr	=	scoreStr.concat("<br>");
				count++;		
			}
			txt.htmlText		=	str;
			scoreTxt.htmlText	=	scoreStr;
		}
		
		/**
		 * 棋子变换数据，(递归)
		 * @param arr
		 * @param legth 每颗棋子所占信息的长度 
		 */		
		private function changeChess(allarr:Array,index:int,length:int):void
		{
			if( index >= allarr.length )
			{
				beginGame(true);
				//ui.chessGroup.mouseChildren	=	true;
				return
			}
			var arr:Array	=	allarr[index];
		
			var mc:MovieClip;
			for(var j:int = 0; j < arr.length;j+=length)
			{	
				(chessArr[int(arr[j])][int(arr[j+1])] as MovieClip).gotoAndStop(3)
			}
			setTimeout(	function ():void
			{
				for(var k:int = 0; k < arr.length;k+=length)
				{
					mc	=	chessArr[int(arr[k])][int(arr[k+1])] as MovieClip;
					mc.visible	=	true;
					mc.gotoAndStop(int(arr[k+2]));
					//(mc.getChildAt(0)as MovieClip).stop();
				}
//				setTimeout(	function ():void
//				{					
					changeChess(allarr,index+1,length);
//				},1000);
				
			},800);	
		}
		
		public function AfterHide():void
		{
			_CDtimer.stop();
			//isCanSeeChess();
		}
			
		private function loadChess():void
		{
			_chessInfoArr	=	[];
		//	updataView();
			if(chessboard == null)
			{
				//SwfLoader.StartLoad("res/swf/chess.swf",null,loadChessboardFun);
//				MiniLoadingBar.getInstance().show("加载中....");
//				SwfLoader.StartLoad(StageInfo.swfResPath + "chess.swf",null,loadChessboardFun,[onLoading]);
				loadChessboardFun()
			}
			else
			{
				if(_model.scene.Role.GetProperties("IsChessStarted") == 0)
				{
					ui.beginBtn.visible	=	true;
					ui.shortBtn.visible	=	true;
				}
				SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_OPEN_CHESS);
			}
		}

		private function onLoading(e:Event):void
		{
			
			var pe:ProgressEvent=e as ProgressEvent;
			if(pe)
				MiniLoadingBar.getInstance().progress=pe.bytesLoaded/pe.bytesTotal;
		}
		
		private function loadChessboardFun():void
		{
			var mc:MovieClip = MultLoader.getInstance().getSourceByUrl(StageInfo.swfResPath + "chess.swf");
			
			SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_OPEN_CHESS);
			//请求排行榜数据
			SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_GET_CHESS_SCORE_TOPLIST);
			(mc.getChildByName("txt5") as TextField).htmlText	=	"";
			(mc.getChildByName("txt6") as TextField).htmlText	=	"";
			mc.addChild(ui.chessGroup);
			ui.chessGroup.x	=		mc["mcx"].x;
			ui.chessGroup.y	=		mc["mcx"].y;
			mc.x			=		ui.chessCont.x;
			mc.y			=		ui.chessCont.y;
			ui.windowBG.addChild(mc);	
			ui.windowBG.addChild(ui.beginBtn);
			ui.windowBG.addChild(ui.shortBtn);
			chessboard			=	mc;
			for(var i:int = 1;i < 5;i++)
			{
				(chessboard.getChildByName("txt"+i) as TextField).text			=	"";
				(chessboard.getChildByName("txt"+i) as TextField).mouseEnabled	=	false;
				(chessboard.getChildByName("txt"+i) as TextField).filters 		= [ NxLabel.glow ];
			}
			updataView();
		}
		
	
		private function initGroup():void
		{
			var mc:MovieClip;
			for(var i:int =0;i < 6; i++)
			{
				var tempArr:Array	=	new Array();
				for(var j:int = 0;j < 6; j++)
				{
					var index:int	=	i*6+j;
					var point:Point	=	new Point(i,j);
					mc	=	ui.chessGroup.getChildAt(index) as MovieClip;
					mc.buttonMode	=	true;
					mc.filters		=	[];
					mc.visible		=	false;
					tempArr.push(mc);
					mc["data"]		=	point;
					mc["fg"].visible	=	false;
					mc.addEventListener(MouseEvent.CLICK,onMouseClickHandle);
					mc.addEventListener(MouseEvent.ROLL_OVER,onMouseOverHandle);
					mc.addEventListener(MouseEvent.ROLL_OUT,onMouseOutHandle);
				}
				chessArr.push(tempArr);
			}
		}
		
		/**
		 * 棋子点击 
		 * @param e
		 * 
		 */		
		private function onMouseClickHandle(e:MouseEvent):void
		{
			//ui.chessGroup.mouseChildren	=	false;
			//var whiteMC:MovieClip	=	new MovieClip();
			var mc:MovieClip			=	e.currentTarget as MovieClip;
			mc.visible	=	false;
			var index:Point 			=	mc["data"];
			if(mc.currentFrame == 1)
			{
				ui.whiteChess.visible	=	true;
				ui.whiteChess.x		=	mc.x;
				ui.whiteChess.y		=	mc.y;
				//chessArr[index.x][index.y].gotoAndStop(2);
				ui.whiteChess.gotoAndPlay(1);
				ui.whiteChess.addFrameScript(ui.whiteChess.totalFrames-1,
					function ():void
					{
						ui.whiteChess.visible	=	false;
						ui.whiteChess.gotoAndStop(1);
						mc.visible	=	true;
						mc.gotoAndStop(2)
						//chessArr[index.x][index.y].gotoAndStop(2);
						SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_ATTACK_CHESS,index.x,index.y);		
					}
					);		
			}
			else if(mc.currentFrame == 2)
			{
				ui.blackChess.visible	=	true;
				ui.blackChess.x		=	mc.x;
				ui.blackChess.y		=	mc.y;
				ui.blackChess.gotoAndPlay(1);
				ui.blackChess.addFrameScript(ui.blackChess.totalFrames-1,
					function ():void
					{
						ui.blackChess.visible	=	false;
						ui.blackChess.gotoAndStop(1);
						mc.visible	=	true;
						mc.gotoAndStop(1);
						//chessArr[index.x][index.y].gotoAndStop(1);
						SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_ATTACK_CHESS,index.x,index.y);		
					}
				);	
			}
			beginGame();
			//chechAll();	
		}
		
		/**
		 * 
		 * @param e
		 * 
		 */		
		private function onMouseOverHandle(e:MouseEvent):void
		{	
			var mc:MovieClip	=	e.target as MovieClip;
			mc["fg"].visible	=	true;
		}
		
		/**
		 * 
		 * @param e
		 * 
		 */		
		private function onMouseOutHandle(e:MouseEvent):void
		{
			var mc:MovieClip	=	e.target as MovieClip;
			mc["fg"].visible	=	false;
		}
			
		private function addEvent():void
		{
			//_timer.addEventListener(TimerEvent.TIMER,dalayHandle);
			_CDtimer.addEventListener(TimerEvent.TIMER,CDtimeHandle);
			ui.beginBtn.addEventListener(MouseEvent.CLICK,onBeginClickHandle);
			_ui.windowBG.addEventListener(NxWindowEvent.WINDOW_CLOSE,onColseClickHandle);
			ui.shortBtn.addEventListener(MouseEvent.CLICK,onShortClickHandle);
			ui.shortBtn.addEventListener(MouseEvent.ROLL_OVER,onShortOverHandle);
			ui.shortBtn.addEventListener(MouseEvent.ROLL_OUT,onShortOutHandle);
			(chessboard.getChildByName("btn1") as SimpleButton).addEventListener(MouseEvent.ROLL_OVER,onBnt1MouseOver);
			(chessboard.getChildByName("btn2") as SimpleButton).addEventListener(MouseEvent.ROLL_OVER,onBtn2MouseOver);
			(chessboard.getChildByName("btn1") as SimpleButton).addEventListener(MouseEvent.ROLL_OUT,onShortOutHandle);
			(chessboard.getChildByName("btn2") as SimpleButton).addEventListener(MouseEvent.ROLL_OUT,onShortOutHandle);
		}
		
		private function dalayHandle(e:TimerEvent):void
		{
			SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_FILL_EMPTY_POS)
		}
		
		private function CDtimeHandle(e:TimerEvent = null):void
		{
			_CDTimeCount--;
			if(_CDTimeCount < 0)
			{
				_CDtimer.stop();
				_CDTimeCount		=	0;
			}
			(chessboard.getChildByName("txt1")as TextField).text =	PlayCDTimerLogic.getInstance().getTimerStr(_CDTimeCount);
			
		}
		/**
		 * 是否开始游戏 
		 * @param e
		 * 
		 */		
		private function isBegin(e:CustomMsgEvent):void
		{
			//请求服务器时间
			_overTime			=	e.pList[0];
			SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_QUERYSERVERTIME);
		}
		
		private function onBeginClickHandle(e:MouseEvent):void
		{
			ui.beginBtn.visible	=	false;
			ui.shortBtn.visible	=	false;
			beginGame(true);
			SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_START_CHESS);
			
		}
		
		/**
		 * 棋子是否可以点击 
		 * @param bool
		 * 
		 */			
		private function beginGame(bool:Boolean = false):void
		{
			for(var i:int =0;i < 6; i++)
			{
				for(var j:int = 0;j < 6; j++)
				{
					(chessArr[i][j] as MovieClip).mouseChildren	= (chessArr[i][j] as MovieClip).mouseEnabled=	bool;
				}
			}
		}
		
		/**
		 * 棋子是否可见
		 * @param bool
		 * 
		 */		
		private function isCanSeeChess(bool:Boolean = false):void
		{
			for(var i:int =0;i < 6; i++)
			{
				for(var j:int = 0;j < 6; j++)
				{
					(chessArr[i][j] as MovieClip).visible	=	bool;
				}
			}
		}
		
		private function onColseClickHandle(e:NxWindowEvent):void
		{
			ui.hide();
		}
		
		/**
		 * 一键收取键点击 
		 * @param e
		 * 
		 */		
		private function onShortClickHandle(e:MouseEvent):void
		{
			SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_ONEKEY_GETPRIZE);
		}
		
		/**
		 * 一键领取TIPs 
		 * @param e
		 * 
		 */		
		private function onShortOverHandle(e:MouseEvent):void
		{
			var maxScore:int	=	_model.scene.Role.GetProperties("ChessMaxScore");	
			var money:int	=	_model.scene.roleLevel *800;
			TipsManage.showTips(StaticIni.getSwfLangStrVar("UIString_1000420",[money]));
		}
		
		private function onBnt1MouseOver(e:MouseEvent):void
		{
			TipsManage.showTips(StaticIni.getSwfLangStr("UIString_1000500"));
		}
		
		private function onBtn2MouseOver(e:MouseEvent):void
		{
			TipsManage.showTips(StaticIni.getSwfLangStr("UIString_1000499"));
		}
		/**
		 * 关闭TIPs 
		 * @param e
		 * 
		 */	
		private function onShortOutHandle(e:MouseEvent):void
		{
			TipsManage.hideTips();
		}
		/**
		 * 分数绑定 
		 * @param val
		 * 
		 */		
		public function set bindScoreCall(val:int):void
		{
			_score	=	val;
			(chessboard.getChildByName("txt2")as TextField).text	=	val.toString();
			
			//(chessboard.getChildByName("txt4")as TextField).text	=	money.toString();
		}
		
		/**
		 * 铜钱绑定 
		 * @param val
		 * 
		 */		
		public function set bindGoldCall(val:int):void
		{
			(chessboard.getChildByName("txt3")as TextField).text	=	val.toString();
		}
		
		public function get ui():GobangUI
		{
			if(_ui == null)
			{
				_ui	=	new GobangUI();
			}
			return _ui
		}
	}
}